﻿using Microsoft.AspNetCore.Mvc;
using bpms.Service;
using System.IO;

namespace bpms.Controllers
{
    /// <summary>
    /// 备份还原模块
    /// </summary>
    public class BackupDBLogController : BaseController
    {
        private readonly BackupDBLogService _backupDBLogService;
        private readonly IConfiguration _config;
        public BackupDBLogController(BackupDBLogService service, IConfiguration config)
        {
            _backupDBLogService = service;
            _config = config;
        }
        public IActionResult Index()
        {
            var backupdir = _config["BackupConfig:backup_path"];
            var backups = _backupDBLogService.GetAll(backupdir);
            return View(backups);
        }

        public IActionResult Create()
        {
            try
            {
                //目录不存在则创建
                var backupdir = _config["BackupConfig:backup_path"];
                Directory.CreateDirectory(backupdir);

                var backupPath =  Path.Combine(backupdir, "mysql_backup_"+DateTime.Now.ToString("yyyyMMddHHmmss")+".sql"); ;
                var server = _config["BackupConfig:server"];
                var database = _config["BackupConfig:database"];
                var user = _config["BackupConfig:user"];
                var password = _config["BackupConfig:password"];
                var mysqldump = _config["BackupConfig:mysqldump"];
                var mysqlexe = _config["BackupConfig:mysqlexe"];
                var type = 1;
                _backupDBLogService.BackupMySqlDatabase(server, database, user, password, backupPath, type, mysqldump);
                TempData["SuccessMessage"] = "备份创建成功！";
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = $"备份失败：{ex.Message}";
            }
          
            return RedirectToAction(nameof(Index));
        }

        public IActionResult Restore(string filePath)
        {
            try
            {
                var server = _config["BackupConfig:server"];
                var database = _config["BackupConfig:database"];
                var user = _config["BackupConfig:user"];
                var password = _config["BackupConfig:password"];
                var mysqlexe = _config["BackupConfig:mysqlexe"];
                var dbName = _config["BackupConfig:DBName"];
                _backupDBLogService.RestoreMySqlDatabase(server, database, user, password, filePath, mysqlexe);
                TempData["SuccessMessage"] = "数据库还原成功！";
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = $"还原失败：{ex.Message}";
            }

            return RedirectToAction(nameof(Index));
        }
    }
}
